var express = require('express');
var router = express.Router();
var createError = require('http-errors');
var mysql = require('../mysql/fun.js');
//需要登录的路由
var userlogin = ['index','shopcard'];
/**
 * 判断用户是否登录
 */
router.use(function (req, res, next) {
  var islogin = false;
  for (var i = 0; i < userlogin.length; i++) {
    if (userlogin[i] == req.path.substring(1)) {
      islogin = true;
    }
  };
  if (islogin) {
    if (req.session.username) {
      return next();
    } else {
      return res.send(`<script>alert('您还没有登录，请先登录');location.href='/login'</script>`);
    }
  }
  next();
})
/**
 * 重定向于主页
 */
router.get('/', function (req, res, next) {
  res.redirect('/index');
})
/**
 * 返回主页面
 */
router.get('/index', function (req, res, next) {
  mysql.commodityall(function (err, data) {
    if (err) {
      return res.render('error.html');
    }
    mysql.swiperall(function (err, swiper) {
      if (err) {
        return res.render('error.html');
      }
      res.render('index.html', {
        username: req.session.username,
        data: data,
        swiper: swiper
      });
    })
  })
});
/**
 * 返回登录界面
 */
router.get('/login', function (req, res, next) {
  res.render('login.html');
});
/**
 * 购物车界面
 */
router.get('/shopcard', function (req, res, next) {
  mysql.showcardbyallbyname(req.session.username, function (err, data) {
    //获得全部的数据
    if (data) {
      data.forEach(function (item) {
        item.comm = JSON.parse(item.comm)
      });
    }
    if (err) {
      return res.render('error.html');
    }
    res.render('shopcard.html', {
      username: req.session.username,
      data: data
    });
  })
})
/**
 * 详情页面
 */
router.get('/info', function (req, res, next) {
  let id = req.query.id
  mysql.commoditybyid(id, function (err, data) {
    if (err) {
      return res.render('error.html');
    }
    data[0].urlList = JSON.parse(data[0].urlList)
    res.render('info.html', {
      info: data[0],
      username: req.session.username,
    });
  })
});
/**
 * 购物车
 */
router.get('/card', function (req, res, next) {
  res.render('card.html',{
    username: req.session.username,
  });
});

module.exports = router;
